package net.oschina.app.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.adapter.ListViewActiveAdapter;
import net.oschina.app.bean.Active;
import net.oschina.app.bean.ActiveList;
import net.oschina.app.bean.Notice;
import net.oschina.app.bean.Result;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import net.oschina.app.widget.NewDataToast;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class BaseActiveListFragment extends MainPullToRefreshListFragment {
	private ListViewActiveAdapter lvActiveAdapter;
	private List<Active> lvActiveData = new ArrayList<Active>();
	private int lvActiveSumData;
	private Handler lvActiveHandler;
	private int curActiveCatalog;
	private boolean isClearNotice = false;
	private int curClearNoticeType = 0;
	
	public BaseActiveListFragment(int curActiveCatalog,
			OnBaseListFragmentResumeListener baseListFragmentResumeListener) {
		super(baseListFragmentResumeListener);
		this.curActiveCatalog = curActiveCatalog;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initActiveListView();
	}

	@Override
	public void onDestroyView() {
		lvActiveData.clear();
		super.onDestroyView();
	}

	/**
	 * 初始化动态列表
	 */
	private void initActiveListView() {
		lvActiveAdapter = new ListViewActiveAdapter(getActivity(),
				lvActiveData, R.layout.active_listitem);
		listView.addFooterView(list_footer);// 添加底部视图 必须在setAdapter前
		listView.setAdapter(lvActiveAdapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 点击头部、底部栏无效
				if (view == list_footer)
					return;

				Active active = null;
				// 判断是否是TextView
				if (view instanceof TextView) {
					active = (Active) view.getTag();
				} else {
					TextView tv = (TextView) view
							.findViewById(R.id.active_listitem_username);
					active = (Active) tv.getTag();
				}
				if (active == null)
					return;

				// 跳转
				UIHelper.showActiveRedirect(view.getContext(), active);
			}
		});
		listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {

				// 数据为空--不用继续下面代码了
				if (lvActiveData.isEmpty())
					return;

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(list_footer) == view
							.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = StringUtils.toInt(listView.getTag());
				if (scrollEnd && lvDataState == UIHelper.LISTVIEW_DATA_MORE) {
					listView.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					list_foot_more.setText(R.string.load_ing);
					list_foot_progress.setVisibility(View.VISIBLE);
					// 当前pageIndex
					int pageIndex = lvActiveSumData / AppContext.PAGE_SIZE;
					loadLvActiveData(curActiveCatalog, pageIndex,
							lvActiveHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});

		lvActiveHandler = this.getLvHandler(listView, lvActiveAdapter,
				list_foot_more, list_foot_progress, AppContext.PAGE_SIZE);
	}

	/**
	 * 线程加载动态数据
	 * 
	 * @param catalog
	 * @param pageIndex
	 *            当前页数
	 * @param handler
	 * @param action
	 */
	private void loadLvActiveData(final int catalog, final int pageIndex,
			final Handler handler, final int action) {
		mPullToRefreshAttacher.setRefreshing(true);
		new Thread() {
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH
						|| action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				try {
					ActiveList list = appContext.getActiveList(catalog,
							pageIndex, isRefresh);
					msg.what = list.getPageSize();
					msg.obj = list;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;
				msg.arg2 = UIHelper.LISTVIEW_DATATYPE_ACTIVE;
				if (curActiveCatalog == catalog)
					handler.sendMessage(msg);
			}
		}.start();
	}

	/**
	 * listview数据处理
	 * 
	 * @param what
	 *            数量
	 * @param obj
	 *            数据
	 * @param objtype
	 *            数据类型
	 * @param actiontype
	 *            操作类型
	 * @return notice 通知信息
	 */
	private Notice handleLvData(int what, Object obj, int objtype,
			int actiontype) {
		Notice notice = null;
		switch (actiontype) {
		case UIHelper.LISTVIEW_ACTION_INIT:
		case UIHelper.LISTVIEW_ACTION_REFRESH:
		case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
			int newdata = 0;// 新加载数据-只有刷新动作才会使用到
			switch (objtype) {
			case UIHelper.LISTVIEW_DATATYPE_ACTIVE:
				ActiveList alist = (ActiveList) obj;
				notice = alist.getNotice();
				lvActiveSumData = what;
				if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH) {
					if (lvActiveData.size() > 0) {
						for (Active active1 : alist.getActivelist()) {
							boolean b = false;
							for (Active active2 : lvActiveData) {
								if (active1.getId() == active2.getId()) {
									b = true;
									break;
								}
							}
							if (!b)
								newdata++;
						}
					} else {
						newdata = what;
					}
				}
				lvActiveData.clear();// 先清除原有数据
				lvActiveData.addAll(alist.getActivelist());
				break;
			}
			if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH && isVisible()) {
				// 提示新加载数据
				if (newdata > 0) {
					NewDataToast
							.makeText(
									getActivity(),
									getString(R.string.new_data_toast_message,
											newdata), appContext.isAppSound())
							.show();
				} else {
					NewDataToast.makeText(getActivity(),
							getString(R.string.new_data_toast_none), false)
							.show();
				}
			}
			break;
		case UIHelper.LISTVIEW_ACTION_SCROLL:
			switch (objtype) {
			case UIHelper.LISTVIEW_DATATYPE_ACTIVE:
				ActiveList alist = (ActiveList) obj;
				notice = alist.getNotice();
				lvActiveSumData += what;
				if (lvActiveData.size() > 0) {
					for (Active active1 : alist.getActivelist()) {
						boolean b = false;
						for (Active active2 : lvActiveData) {
							if (active1.getId() == active2.getId()) {
								b = true;
								break;
							}
						}
						if (!b)
							lvActiveData.add(active1);
					}
				} else {
					lvActiveData.addAll(alist.getActivelist());
				}
				break;
			}
			break;
		}
		return notice;
	}

	/**
	 * 获取listview的初始化Handler
	 * 
	 * @param lv
	 * @param adapter
	 * @return
	 */
	protected Handler getLvHandler(final ListView lv,
			final BaseAdapter adapter, final TextView more,
			final ProgressBar progress, final int pageSize) {
		return new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what >= 0) {
					// listview数据处理
					Notice notice = handleLvData(msg.what, msg.obj, msg.arg2,
							msg.arg1);

					if (msg.what < pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_FULL);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_full);
					} else if (msg.what == pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_more);
					}
					// 发送通知广播
					if (notice != null) {
						UIHelper.sendBroadCast(lv.getContext(), notice);
					}
					 //是否清除通知信息
					 if (isClearNotice) {
						 ClearNotice(curClearNoticeType);
						 isClearNotice = false;// 重置
						 curClearNoticeType = 0;
					 }
				} else if (msg.what == -1) {
					// 有异常--显示加载出错 & 弹出错误消息
					lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
					more.setText(R.string.load_error);
					((AppException) msg.obj).makeToast(getActivity());
				}
				if (adapter.getCount() == 0) {
					lv.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					more.setText(R.string.load_empty);
				}
				progress.setVisibility(ProgressBar.GONE);
				mPullToRefreshAttacher.setRefreshComplete();
				if (msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH) {
					// getFragmentActivity().setActionBarSubtitle(getString(R.string.pull_to_refresh_update)
					// + new Date().toLocaleString());
					lv.setSelection(0);
				} else if (msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG) {
					lv.setSelection(0);
				}
			}
		};
	}

	@Override
	public void onRefreshStarted(View view) {
		// 是否处理通知信息
		if (curActiveCatalog == ActiveList.CATALOG_ATME) {
			this.isClearNotice = true;
			this.curClearNoticeType = Notice.TYPE_ATME;
		} else if (curActiveCatalog == ActiveList.CATALOG_COMMENT) {
			this.isClearNotice = true;
			this.curClearNoticeType = Notice.TYPE_COMMENT;
		} 
		loadLvActiveData(curActiveCatalog, 0, lvActiveHandler,
				UIHelper.LISTVIEW_ACTION_REFRESH);
	}

	@Override
	public void showList() {
		if (!appContext.isLogin()) {
			UIHelper.showLoginDialog(getActivity());
			return;
		}
		if (!isHasInit()) {
			loadLvActiveData(curActiveCatalog, 0, lvActiveHandler,
					UIHelper.LISTVIEW_ACTION_INIT);
			setHasInit(true);
		}
	}
	
	/**
	 * 通知信息处理
	 * 
	 * @param type
	 *            1:@我的信息 2:未读消息 3:评论个数 4:新粉丝个数
	 */
	private void ClearNotice(final int type) {
		final int uid = appContext.getLoginUid();
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1 && msg.obj != null) {
					Result res = (Result) msg.obj;
					if (res.OK() && res.getNotice() != null) {
						UIHelper.sendBroadCast(getActivity(), res.getNotice());
					}
				} else {
					((AppException) msg.obj).makeToast(getActivity());
				}
			}
		};
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Result res = appContext.noticeClear(uid, type);
					msg.what = 1;
					msg.obj = res;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
}
